var _itkl = {};
layui.use(['form', 'laydate', 'layer', 'upload', 'element', 'table'], function () {

    layui.laytpl.toDateString = function(d, format){
        var date = new Date(d || new Date())
            ,ymd = [
            this.digit(date.getFullYear(), 4)
            ,this.digit(date.getMonth() + 1)
            ,this.digit(date.getDate())
        ]
            ,hms = [
            this.digit(date.getHours())
            ,this.digit(date.getMinutes())
            ,this.digit(date.getSeconds())
        ];

        format = format || 'yyyy-MM-dd HH:mm:ss';

        return format.replace(/yyyy/g, ymd[0])
            .replace(/MM/g, ymd[1])
            .replace(/dd/g, ymd[2])
            .replace(/HH/g, hms[0])
            .replace(/mm/g, hms[1])
            .replace(/ss/g, hms[2]);
    };

    //数字前置补零
    layui.laytpl.digit = function(num, length, end){
        var str = '';
        num = String(num);
        length = length || 2;
        for(var i = num.length; i < length; i++){
            str += '0';
        }
        return num < Math.pow(10, length) ? str + (num|0) : num;
    };

    var laydate = layui.laydate;
    var form = layui.form;
    var upload = layui.upload;
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var tableData = {};
    var moveLoading = '';
    var movePage = '';
    _itkl = {
        permission: {
            openPermissionSetPage: function(fileId){
                //打开权限设置页面：
                var w = ($(window).width()*0.8);
                var h = ($(window).height()*0.8);
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shade: 0.8,
                    area: [w+'px',h+'px'],
                    content: '/it/dic/permission/page?id='+fileId,
                    success: function(layero, index){
                        movePage = index;
                    },
                    end: function () {
                        _itkl.content.flushTable('fileList');
                    }
                });
            },
            initPermissionCheckbox: function(){
                _itkl.permission.allCheckBoxAction();
            },
            allCheckBoxAction: function(){
                $('.checkAllBox').on('click',function(){
                    if($(this).is(':checked')){
                        $('.'+$(this).attr('tarbox')).prop('checked',true);
                    }else{
                        $('.'+$(this).attr('tarbox')).prop('checked',false);
                    }
                })
            }
        },
        content: {
            leftOpen: function(dicId){
              //打开某一个:

            },
            leftCloseAll: function(){
                $('.oneLevelLi').removeClass('layui-nav-itemed');
                $('.twoLevelLi').removeClass('layui-nav-itemed');
            },
            leftOpenAll: function(){
                $('.oneLevelLi').addClass('layui-nav-itemed');
                $('.twoLevelLi').addClass('layui-nav-itemed');
            },
            setFileListTable: function(dicId,onlyZskUser){
                var theCols ;

                    theCols = [[
                        {checkbox: true, fixed: true, width: '5%',align: 'center'},
                        {field: 'fileName', title: '名称', width: '25%',align: 'center',templet: '#nameTpl'},
                        {field: 'createUsername', title: '创建人', width: '9%',align: 'center'},
                        {field: 'createDate', title: '创建时间', width: '14%', sort: true,templet: '<div>{{ layui.laytpl.toDateString(d.createDate,"yyyy-MM-dd") }}</div>',align: 'center'},
                        {field: 'text', title: '操作', width: '47%', toolbar:'#toolBar',align: 'center'}
                    ]];

                table.render({
                    id: 'fileList',
                    elem: '#fileList',
                    url: '/it/dicContent/'+dicId,
                    skin: 'nob',
                    cols:theCols,
                    height: 'full-10',
                    page: true,
                    done: function(res,curr,count){
                        tableData = res.data;
                    }
                })

                table.on('tool(fileList)', function (obj) {
                    var data = obj.data;
                    var fileId = data.id;
                    var zskfiletype = data.zskfileType;
                    var fileName = data.fileName;
                    if (obj.event === 'del') {
                        if(!zskfiletype){
                            layer.msg('文件类型缺失',{icon:2});
                            return ;
                        }
                        if(zskfiletype == '1'){
                            //判断该文件夹下面是否有东西,有的话提示,不允许删除
                            var canDel = _itkl.file.checkCanDel(fileId);
                        }else if(zskfiletype == '2'){
                            //带着id去后端伪删除
                            _itkl.file.del(fileId);
                        }
                    }else if(obj.event === 'move'){
                        localStorage.setItem("movefromfileid",data.id);
                        localStorage.setItem("movefromfilename",data.fileName);
                        var filetype = "文件";
                        if(data.zskfileType == '1'){
                            filetype = '文件夹';
                        }
                        localStorage.setItem("movefromzskfiletype",filetype);
                        //打开目录树页面：
                        var w = ($(window).width()*0.4);
                        var h = ($(window).height()*0.8);
                        layer.open({
                            type: 2,
                            title: false,
                            closeBtn: 1,
                            shade: 0.8,
                            area: [w+'px',h+'px'],
                            content: '/it/dic/showDicTree?id='+fileId,
                            success: function(layero, index){
                                movePage = index;
                            },
                            end: function () {
                            }
                        });
                    }else if(obj.event === 'setQX'){
                        //权限设置
                        _itkl.permission.openPermissionSetPage(fileId);
                    }else if(obj.event === 'download'){
                        if("1" == zskfiletype){
                            //压缩,下载文件夹
                            _itkl.file.muldown('fileId');
                        }else if('2' == zskfiletype){
                            //下载文件
                            window.open("/supervisor/projectManager/exportFile?id=" + fileId);
                        }else{
                            layer.msg('没有识别文件或文件夹,请联系管理员维护',{icon:2});
                            return ;
                        }
                    }else if(obj.event === 'setJS'){
                        localStorage.setItem("setjspage",'2');
                        layer.open({
                            type: 2,
                            area: ['380px', '250px'],
                            fix: false,
                            shadeClose: false,
                            shade: 0.4,
                            title: "检索设置",
                            content: '/it/file/searching?id='+fileId,
                            yes: function(){
                                alert(8888);
                            },
                            btn2: function(){
                                layer.closeAll();
                            },
                            zIndex: layer.zIndex, //重点1,
                            success: function(layero){
                                layer.setTop(layero); //重点2
                            }
                        });
                    }else if(obj.event === 'editForm'){
                        _itkl.form.showEdit(fileId);
                    }
                });
            },
            jumpTo: function(fileId,zskfiletype,fileName){
                if(zskfiletype == '1'){
                    //文件列表页面
                    window.parent._showtab(fileId,fileName,"/it/dic/"+fileId,function(iframe){
                        if(iframe){
                            $(iframe)[0].contentWindow.flushTable();
                        }
                    });
                }else if(zskfiletype == '2'){
                    //文件详情页
                    window.parent._showtab(fileId,fileName,"/it/file/particulars?id="+fileId,function(iframe){
                        if(iframe){
                            $(iframe)[0].contentWindow.flushPage();
                        }
                    });
                    //增加文件浏览量:
                    _itkl.file.addViewCount(fileId);
                }else{
                    layer.msg('未知点击的是文件还是文件夹',{icon:2});
                }
            },
            flushTable: function(tableId){
                table.reload(tableId);
            },
            flushTableWithSearchKey: function(tableId,searchKey){
                table.reload(tableId,{
                    where: {
                        fileName: searchKey
                    }
                });
            },
            flushTableWithoutSearchKey: function(tableId,searchKey){
                table.reload(tableId,{
                    where: {
                        fileName: ''
                    }
                });
            },
            layerClose: function(){
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            }
        },
        file: {
            addDownloadCount: function(fileId){
              //增加文件下载量:
              $.ajax({
                  url: '/it/addDownloads',
                  data: {fileId: fileId},
                  type: 'post',
                  dataType: 'json',
                  success: function(res){
                  },
                  error: function(res){
                  }
              })
            },
            addViewCount: function(fileId){
                //增加文件浏览量
                $.ajax({
                    url: '/it/addViewCount',
                    data: {fileId: fileId},
                    type: 'post',
                    dataType: 'json',
                    success: function(res){
                    },
                    error: function(res){
                    }
                })
            },
            move: function(sourceFileId,targetFileId){
                //开启等待（因为不知道移动的啥。。。）;
                moveLoading = layer.msg('移动中。。。', {
                    icon: 16
                    , shade: 0.2,
                    time: false
                });
                //带着参数给后端
                $.ajax({
                    url: '/it/dic/move',
                    data: {sourceFileId: sourceFileId,targetFileId: targetFileId},
                    type: 'post',
                    dataType: 'json',
                    async: false,
                    success: function(res){
                        if(res.flag){
                            layer.msg('操作成功',{icon:1});
                            setTimeout(function(){
                                parent.parent.delOneDic(sourceFileId);
                                localStorage.setItem('newitdicfileid', res.data.id);
                                localStorage.setItem('newitdicfilename',res.data.filename);
                                parent.parent.addLeft(targetFileId);
                                parent.layer.closeAll();
                                layer.closeAll();
                                parent.flushTable();
                            },1500);
                            //todo: 操作左侧目录树
                        }else{
                            layer.close(moveLoading);
                            layer.msg(res.msg,{icon:2});
                            return ;
                        }
                    }
                })
                //得到后端处理结果后。。


            },
            del: function(fileId){
                layer.confirm('确定删除吗?', function(index){
                    if(fileId){
                        //带着id去后端伪删除
                        $.ajax({
                            url: '/it/dic/del/'+fileId,
                            type: 'post',
                            dataType: 'json',
                            success: function(res){
                                if(res.flag){
                                    layer.msg('删除成功',{icon:1});
                                    parent.parent.delOneDic(fileId);
                                    //刷新表格:
                                    _itkl.content.flushTable('fileList');
                                    setTimeout(function(){
                                        layer.close(index);
                                    },1500);
                                }else{
                                    layer.msg(res.msg,{icon:2});
                                    return ;
                                }
                            }
                        })
                    }

                });
            },
            checkCanDel: function(dicId){
              //判断是否可以删除
              //如果包含下级文件不允许删除
              $.ajax({
                  url: '/it/dic/checkCanDel',
                  data: {id: dicId},
                  type: 'get',
                  async: false,
                  dataType: 'json',
                  success: function(res){
                      if(!res.flag){
                          layer.msg(res.msg,{icon:2});
                          return false;
                      }else{
                          _itkl.file.del(dicId);
                      }
                  }
              })
            },
            muldown: function(dicId){
              //批量下载：
                //获取需要下载的文件id:
                var checkFileId = '';
                $.each(tableData,function(i,e){
                    if(e.LAY_CHECKED){
                        checkFileId = checkFileId + "," + e.id;
                    }
                })
                if(checkFileId){
                    window.open("/it/dic/download?dicId=" + dicId+"&fileIds="+checkFileId);
                }else{
                    layer.msg("请先选择需要下载的文件",{icon:2});
                    return ;
                }
            },
            showUpload: function(dicId){
                var w = ($(window).width()*0.8);
                var h = ($(window).height()*0.8);
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shade: 0.8,
                    area: [w+'px',h+'px'],
                    content: '/it/dic/showUpload?dicId='+dicId,
                    end: function () {
                        _itkl.content.flushTable('fileList');
                    }
                });
            },
            newDic: function(dicId){
                var w = ($(window).width()*0.8);
                var h = ($(window).height()*0.8);
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shade: 0.8,
                    area: [w+'px',h+'px'],
                    content: '/it/dic/newDic?dicId='+dicId,
                    end: function () {
                    }
                });
            },
            recycle: function(){
                //跳转到回收站页面
                window.parent._showtab("itrecycle123",'文件回收站','/it/file/recycle',function(iframe){
                    if(iframe){
                        $(iframe)[0].contentWindow.flushTable();
                    }
                });
            },
            getDicSeeRoles: function(){
                var seeCheckboxes = $('.seecheckbox');
                var newSeeRoles = '';
                $.each(seeCheckboxes,function(i,e){
                    var aRoleName = $(e).next().attr('rolename');
                    if($(e).is(":checked")){
                        newSeeRoles = newSeeRoles + ',' + aRoleName;
                    }
                })
                return newSeeRoles;
            },
            getDicDownloadRoles: function(){
                var downloadCheckboxes = $('.downloadcheckbox');
                var newDownloadRoles = '';
                $.each(downloadCheckboxes,function(i,e){
                    var aRoleName = $(e).next().attr('rolename');
                    if($(e).is(":checked")){
                        newDownloadRoles = newDownloadRoles + ',' + aRoleName;
                    }
                })
                return newDownloadRoles;
            },
            getDicNoSeeRoles: function(){
                var noSeeCheckboxes = $('.noseecheckbox');
                var newNoSeeRoles = '';
                $.each(noSeeCheckboxes,function(i,e){
                    var aRoleName = $(e).next().attr('rolename');
                    if($(e).is(":checked")){
                        newNoSeeRoles = newNoSeeRoles + ',' + aRoleName;
                    }
                })
                return newNoSeeRoles;
            },
            saveNewDic: function(dicId){
                var newDicName = $('#newFileName').val();
                //验证新文件夹名称的合法性
                if(!_itkl.file.checkNewDicName(newDicName)){
                    return ;
                };
                //验证新文件夹名称是否重复
                _itkl.file.checkNewDicNameSingle(newDicName,dicId);
            },
            setDicPermission: function(dicId){
                var seeRoles = _itkl.file.getDicSeeRoles();
                var downloadRoles = _itkl.file.getDicDownloadRoles();
                var noseeRoles = _itkl.file.getDicNoSeeRoles();
                var sendData = {
                    id: dicId
                }
                sendData.id = dicId;
                if(seeRoles){
                    sendData.examineUser = seeRoles;
                }else{
                    sendData.examineUser = '';
                }
                if(downloadRoles){
                    sendData.downloadUser = downloadRoles;
                }else{
                    sendData.downloadUser = '';
                }
                if(noseeRoles){
                    sendData.canotSeeRoles = noseeRoles;
                }else{
                    sendData.canotSeeRoles = '';
                }
                sendData.formCode = 'permission';
                moveLoading = layer.msg('设置中,请稍后。。。', {
                    icon: 16
                    , shade: 0.2,
                    time: false
                });
                $.ajax({
                    url: '/it/dic/updateFile',
                    data: sendData,
                    type: 'post',
                    dataType: 'json',
                    success: function(res){
                        if(res.flag){
                            layer.msg("设置成功",{icon:1});
                            //关闭窗口
                            setTimeout(function(){
                                layer.close(moveLoading);
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            },1300)
                            //刷新表格
                        }else{
                            layer.close(moveLoading);
                            layer.msg(res.msg,{icon:2});
                        }
                    },error: function(res){
                        layer.close(moveLoading);
                        parent.layer.msg(res.msg,{icon:2});
                    }
                })
            },
            saveNewDicAfterCheck: function(newFileName,dicId){
                //获得查看权限：
                var seeRoles = _itkl.file.getDicSeeRoles();
                var downloadRoles = _itkl.file.getDicDownloadRoles();
                var noseeRoles = _itkl.file.getDicNoSeeRoles();
                var sendData = {
                    superiorId: dicId,
                    fileName: newFileName,
                    zskfileType: '1'
                };
                if(seeRoles){
                    sendData.examineUser = seeRoles;
                }else{
                    sendData.examineUser = '';
                }
                if(downloadRoles){
                    sendData.downloadUser = downloadRoles;
                }else{
                    sendData.downloadUser = '';
                }

                if(noseeRoles){
                    sendData.canotSeeRoles = noseeRoles;
                }else{
                    sendData.canotSeeRoles = '';
                }
                $.ajax({
                    url: '/it/dic/new',
                    data: sendData,
                    type: 'post',
                    dataType: 'json',
                    success: function(res){
                        if(res.flag){
                            parent.flushTable();
                            localStorage.setItem('newitdicfileid',res.data.id);
                            localStorage.setItem('newitdicfilename',res.data.fileName);
                            parent.parent.addLeft(dicId);
                            parent.layer.msg('创建成功',{icon:1});
                            //关闭窗口
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                            //刷新表格
                        }else{
                            layer.msg(res.msg,{icon:2});
                        }
                    },error: function(res){
                        parent.layer.msg(res.msg,{icon:2});
                    }
                })
            },
            checkNewDicName: function(newFileName){
                if(!newFileName){
                    layer.msg("文件夹名称不能为空",{icon:2});
                    return false;
                }
                if(newFileName.length > 128){
                    layer.msg("文件夹名称超长",{icon:2});
                    return false;
                }
                return true;
            },
            checkNewDicNameSingle: function(newFileName,dicId){
              $.ajax({
                  url: '/it/dic/checkName',
                  data: {fileName: newFileName,superiorId:dicId,deleteState:'1',zskfileType:'1'},
                  type: 'get',
                  dataType: 'json',
                  cache: false,
                  async: false,
                  success: function(res){
                      if(!res.flag){
                          layer.msg(res.msg,{icon:2});
                          return false;
                      }else{
                          _itkl.file.saveNewDicAfterCheck(newFileName,dicId);
                      }
                  },
                  error: function(res){
                      layer.msg(res.msg,{icon:2});
                      return false;
                  }
              })
            }
        },
        form: {
            showEdit: function(dicId){
                //表单数据:
                var w = ($(window).width()*0.8);
                var h = ($(window).height()*0.8);
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shade: 0.8,
                    area: [w+'px',h+'px'],
                    content: '/it/form/show?dicId='+dicId+'&edit=1',
                    success: function(layero, index){

                    },
                    end: function () {
                    }
                });
            },
            showForm: function(e,temp,dicId){
                var w = ($(window).width()*0.8);
                var h = ($(window).height()*0.8);
                var formCode = $(e).attr('formcode');
                layer.open({
                    type: 2,
                    title: false,
                    closeBtn: 1,
                    shade: 0.8,
                    area: [w+'px',h+'px'],
                    content: '/it/form/show?formCode='+formCode+'&temp='+temp+'&dicId='+dicId,
                    success: function(layero, index){

                    },
                    end: function () {

                    }
                });
            }
        }
    }
});
